import processing.serial.*;


PImage img;

Serial myPort;  // Create object from Serial class

int sizeScan = 800;
int sizeImg = sizeScan * sizeScan;
int i=sizeImg-1, j=0;    
int inbyte = 0;  

float avr=0;
int minValue = 255;
int maxValue = 0;


void setup() 
{
  size(sizeScan, sizeScan); 
 rectMode(CENTER);
  
  //println(Serial.list());
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 115200);
  
  //delay(10000);
  
  img = createImage(sizeScan, sizeScan, RGB);
  //myPort.write(""+ 2000 + "B");
  //myPort.write("" + sizeScan + "A");
  noCursor();
  
}

void draw() 
{
  
  img.loadPixels();
  if(i<0){ 
      i=sizeImg-1;
      //myPort.write("" + sizeScan + "A");
      //println("average = " + avr/sizeImg);
      //println("maximum = " + maxValue);
      //println("minimum = " + minValue);
      avr = 0;
    }
  while(myPort.available() > 0){ 
   
    inbyte = myPort.read();
   
    // for tests:
    //print((char)inbyte);
     
    avr+=inbyte;
    if(inbyte > maxValue) maxValue = inbyte;
    if(inbyte < minValue) minValue = inbyte;
    //println(int(inbyte));
    img.pixels[i] = color(inbyte);
    i--;
    
    
    
    
  }
  img.updatePixels();
  image(img, 0, 0, sizeScan, sizeScan);
  
  
  stroke(255, 0, 0); noFill();strokeWeight(1);
  //point(mouseX, mouseY);
  rect(mouseX, mouseY,5,5 ); 
  // color co = get(mouseX+1, mouseY);
  // text
}

void keyPressed(){
  if(key == ' ') myPort.write("" + sizeScan + "takeSnapshot/");
}

void mouseReleased(){
  //myPort.write(""+ 2000 + "B");
  //myPort.write("" + sizeScan + "A");
  color co = get(mouseX, mouseY);
  println(red(co));
}

